const express = require('express');
const router = express.Router();
const db = require('../db'); // 使用统一的数据库连接

// 获取所有用户
router.get('/', (req, res) => {
  const sql = 'SELECT * FROM users ORDER BY created_at DESC';
  
  db.query(sql, (err, result) => {
    if (err) {
      console.error('Database error:', err);
      return res.status(500).json({ 
        error: 'Database error',
        message: err.message 
      });
    }
    
    res.json({
      success: true,
      data: result,
      count: result.length
    });
  });
});

// 根据ID获取用户
router.get('/:id', (req, res) => {
  const { id } = req.params;
  const sql = 'SELECT * FROM users WHERE user_id = ?';
  
  db.query(sql, [id], (err, result) => {
    if (err) {
      console.error('Database error:', err);
      return res.status(500).json({ 
        error: 'Database error',
        message: err.message 
      });
    }
    
    if (result.length === 0) {
      return res.status(404).json({ 
        error: 'User not found',
        message: `User with ID ${id} does not exist`
      });
    }
    
    res.json({
      success: true,
      data: result[0]
    });
  });
});

// 创建新用户
router.post('/', (req, res) => {
  const { username, email, password, phone } = req.body;
  
  // 验证必填字段
  if (!username || !email || !password) {
    return res.status(400).json({
      error: 'Validation error',
      message: 'Username, email and password are required'
    });
  }
  
  const sql = 'INSERT INTO users (username, email, password_hash, phone, created_at) VALUES (?, ?, ?, ?, NOW())';
  const values = [username, email, password, phone || null];
  
  db.query(sql, values, (err, result) => {
    if (err) {
      console.error('Database error:', err);
      return res.status(500).json({ 
        error: 'Database error',
        message: err.message 
      });
    }
    
    res.status(201).json({
      success: true,
      message: 'User created successfully',
      data: {
        id: result.insertId,
        username,
        email,
        phone
      }
    });
  });
});

// 更新用户信息
router.put('/:id', (req, res) => {
  const { id } = req.params;
  const { username, email, phone } = req.body;
  
  const sql = 'UPDATE users SET username = ?, email = ?, phone = ?, updated_at = NOW() WHERE user_id = ?';
  const values = [username, email, phone, id];
  
  db.query(sql, values, (err, result) => {
    if (err) {
      console.error('Database error:', err);
      return res.status(500).json({ 
        error: 'Database error',
        message: err.message 
      });
    }
    
    if (result.affectedRows === 0) {
      return res.status(404).json({ 
        error: 'User not found',
        message: `User with ID ${id} does not exist`
      });
    }
    
    res.json({
      success: true,
      message: 'User updated successfully',
      data: {
        id,
        username,
        email,
        phone
      }
    });
  });
});

// 删除用户
router.delete('/:id', (req, res) => {
  const { id } = req.params;
  const sql = 'DELETE FROM users WHERE user_id = ?';
  
  db.query(sql, [id], (err, result) => {
    if (err) {
      console.error('Database error:', err);
      return res.status(500).json({ 
        error: 'Database error',
        message: err.message 
      });
    }
    
    if (result.affectedRows === 0) {
      return res.status(404).json({ 
        error: 'User not found',
        message: `User with ID ${id} does not exist`
      });
    }
    
    res.json({
      success: true,
      message: 'User deleted successfully'
    });
  });
});

const crypto = require('crypto');

// 用户登录接口
router.post('/login', (req, res) => {
  const { username, password } = req.body;
  
  // 验证必填字段
  if (!username || !password) {
    return res.status(400).json({
      error: 'Validation error',
      message: 'Username and password are required'
    });
  }
  
  console.log('Login attempt with username:', username);
  console.log('Input password:', password);
  
  // 查询用户
  const sql = 'SELECT * FROM users WHERE username = ?';
  
  db.query(sql, [username], (err, result) => {
    if (err) {
      console.error('Database error:', err);
      return res.status(500).json({ 
        error: 'Database error',
        message: err.message 
      });
    }
    
    if (result.length === 0) {
      console.log('User not found:', username);
      return res.status(401).json({ 
        error: 'Authentication failed',
        message: 'Invalid username or password'
      });
    }
    
    const user = result[0];
    console.log('User found:', user.username);
    console.log('Stored password:', user.password_hash);
    
    // 直接进行明文密码比较（因为数据库中存储的是明文）
    const passwordMatch = password === user.password_hash;
    console.log('Password match result:', passwordMatch);
    
    // 验证密码
    if (!passwordMatch) {
      console.log('Password validation failed');
      return res.status(401).json({ 
        error: 'Authentication failed',
        message: 'Invalid username or password'
      });
    }
    
    // 生成token
    const token = `token_${user.user_id}_${Date.now()}`;
    
    console.log('Login successful for user:', username);
    return res.json({
      success: true,
      message: 'Login successful',
      data: {
        user_id: user.user_id,
        username: user.username,
        email: user.email,
        phone: user.phone,
        token: token
      }
    });
  });
});

module.exports = router;

